package com.pg.controller.dd;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pg.entity.EipTemp;
import com.pg.entity.dd.EipSalesOrder;
import com.pg.entity.dd.EipWorkOrder;
import com.pg.service.EipTempService;
import com.pg.service.EipWorkOrderService;
import com.pg.utils.PoiReadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 工单前端控制器
 * </p>
 *
 * @author likl
 * @since 2020-07-06
 */
@Api(tags = "工单")
@RestController
@RequestMapping("/eipWorkOrder")
@Slf4j
public class EipWorkOrderController extends JeecgController<EipWorkOrder, EipWorkOrderService> {

    @Autowired
    private EipTempService eipTempService;

    @Autowired
    private EipWorkOrderService eipWorkOrderService;

    /**
     * 添加 工单
     *
     * @param eipWorkOrder 工单
     * @return 是否成功
     */
    @ApiOperation("添加 工单")
    @AutoLog(value = "添加 工单")
    @PostMapping("/add")
    public Result<?> add(@RequestBody EipWorkOrder eipWorkOrder) {
        EipWorkOrder eipWorkOrderByWoNo = eipWorkOrderService.selectByWoNo(eipWorkOrder.getWoNo());
        if (eipWorkOrderByWoNo != null) {
            return Result.error("工单号重复！");
        } else {
            eipWorkOrder.setPuid(UUID.randomUUID().toString());
            eipWorkOrderService.save(eipWorkOrder);
            return Result.ok("添加成功！");
        }
    }

    /**
     * 编辑 工单
     *
     * @param eipWorkOrder 工单
     * @return 是否成功
     */
    @ApiOperation("编辑 工单")
    @AutoLog(value = "编辑 工单")
    @PostMapping("/edit")
    public Result<?> edit(@RequestBody EipWorkOrder eipWorkOrder) {
        eipWorkOrderService.updateById(eipWorkOrder);
        return Result.ok("修改成功！");
    }

    /**
     * 临时编辑 工单
     *
     * @param eipWorkOrder 工单
     * @return 是否成功
     */
    @ApiOperation("临时编辑 工单")
    @AutoLog(value = "DataCheck")
    @RequestMapping(method = RequestMethod.POST, value = "/editTemp")
    public Result<?> editTemp(@Valid @RequestBody EipWorkOrder eipWorkOrder, HttpServletRequest req) {
        String userName = (String) req.getSession().getAttribute("userName");
        EipTemp eipTemp = new EipTemp();
        eipTemp.setDataType("工单");
        eipTemp.setModUser(userName);
        eipTemp.setModTime(new Date());
        eipTemp.setLinkPUID(eipWorkOrder.getPuid());
        eipTemp.setDetailedInformation(JSONObject.toJSONString(eipWorkOrder));
        try {
            eipWorkOrderService.updateWorkOrder(eipTemp);
            return Result.ok("修改成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("修改失败！");
        }
    }

    /**
     * 通过id删除 工单
     *
     * @param id 全库唯一码
     * @return 是否成功
     */
    @ApiOperation("通过id删除 工单")
    @AutoLog(value = "添加 工单")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        eipWorkOrderService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除 工单
     *
     * @param ids 全库唯一码集合
     * @return 是否成功
     */
    @ApiOperation("批量删除 工单")
    @AutoLog(value = "批量删除 工单")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.eipWorkOrderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id逻辑删除 工单
     *
     * @param id 全库唯一码
     * @return 是否成功
     */
    @ApiOperation("通过id逻辑删除 工单")
    @AutoLog(value = "通过id逻辑删除 工单")
    @DeleteMapping(value = "/logicalDelete")
    public Result<?> logicalDelete(@RequestParam(name = "id", required = true) String id) {
        eipWorkOrderService.logicalDelete(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量逻辑删除 工单
     *
     * @param ids 全库唯一码集合
     * @return 是否成功
     */
    @ApiOperation("批量逻辑删除 工单")
    @AutoLog(value = "批量逻辑删除 工单")
    @DeleteMapping(value = "/logicalDeleteBatch")
    public Result<?> logicalDeleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        eipWorkOrderService.logicalDeleteBatch(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }


    /**
     * 通过id查询 工单
     *
     * @param puid 全库唯一码
     * @return 是否成功
     */
    @ApiOperation("通过id查询 工单")
    @AutoLog(value = "DataCheck")
    @RequestMapping(method = RequestMethod.GET, value = "/selectByPuid")
    public Result<?> selectByPuid(@RequestParam(name = "puid") String puid) {
        EipWorkOrder byId;
        byId = eipTempService.selectWorkOrderByLinkPUID(puid);
        if (byId == null) {
            byId = eipWorkOrderService.selectByPuid(puid);
            if (byId == null) {
                return Result.error("未找到对应数据");
            }
        }
        return Result.ok(byId);
    }

    /**
     * 通过工单号查询 工单
     *
     * @param woNo 全库唯一码
     * @return 是否成功
     */
    @ApiOperation("通过工单号查询 工单")
    @AutoLog(value = "通过工单号查询 工单")
    @GetMapping("/selectByWoNo")
    public Result<?> selectByWoNo(@RequestParam(name = "woNo") String woNo) {
        EipWorkOrder byWoNo;
        byWoNo = eipWorkOrderService.selectByWoNo(woNo);
        if (byWoNo == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(byWoNo);
    }

    /**
     * 分页列表查询 工单
     *
     * @param eipWorkOrder        工单
     * @param planStartDateBegin  起始时间
     * @param planStartDateFinish 结束时间
     * @param pageNo              起始页
     * @param pageSize            每页页数
     * @param req                 参数
     * @return 分页数据
     */
    @ApiOperation("分页列表查询 工单")
    @AutoLog(value = "QueryExport")
    @RequestMapping(method = RequestMethod.GET, value = "/list")
    public Result<?> selectForList(
            EipWorkOrder eipWorkOrder,
            @RequestParam(name = "planStartDateBegin", defaultValue = "") @DateTimeFormat(pattern = "yyyy-MM-dd") Date planStartDateBegin,
            @RequestParam(name = "planStartDateFinish", defaultValue = "") @DateTimeFormat(pattern = "yyyy-MM-dd") Date planStartDateFinish,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        if ("undefined".equals(eipWorkOrder.getIpoNo())) {
            eipWorkOrder.setIpoNo(null);
        }
        Page<EipWorkOrder> page = new Page<>(pageNo, pageSize);
        IPage<EipWorkOrder> pageList = eipWorkOrderService.selectForList(page, eipWorkOrder, planStartDateBegin, planStartDateFinish);
        return Result.ok(pageList);
    }

    /**
     * 分页列表查询 工单
     *
     * @param eipWorkOrder        工单
     * @param planStartDateBegin  起始时间
     * @param planStartDateFinish 结束时间
     * @param pageNo              起始页
     * @param pageSize            每页页数
     * @param req                 参数
     * @return 分页数据
     */
    @ApiOperation("分页列表查询 工单")
    @AutoLog(value = "DataCheck")
    @RequestMapping(method = RequestMethod.GET, value = "/checkList")
    public Result<?> checkList(
            EipWorkOrder eipWorkOrder,
            @RequestParam(name = "planStartDateBegin", defaultValue = "") @DateTimeFormat(pattern = "yyyy-MM-dd") Date planStartDateBegin,
            @RequestParam(name = "planStartDateFinish", defaultValue = "") @DateTimeFormat(pattern = "yyyy-MM-dd") Date planStartDateFinish,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        if ("undefined".equals(eipWorkOrder.getIpoNo())) {
            eipWorkOrder.setIpoNo(null);
        }
        Page<EipWorkOrder> page = new Page<>(pageNo, pageSize);
        IPage<EipWorkOrder> pageList = eipWorkOrderService.selectForList(page, eipWorkOrder, planStartDateBegin, planStartDateFinish);
        return Result.ok(pageList);
    }

    /**
     * 通过excel导入数据 工单
     *
     * @param request  参数
     * @param response 响应
     * @return 是否成功
     */
    @ApiOperation("通过excel导入数据 工单")
    @AutoLog(value = "通过excel导入数据 工单")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            String fileName = file.getOriginalFilename();
            String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (!PoiReadUtil.checkExtension(extension)) {
                return Result.error("文件导入失败:文件格式错误");
            }
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<EipWorkOrder> list = ExcelImportUtil.importExcel(file.getInputStream(), EipWorkOrder.class, params);
                for (EipWorkOrder eipWorkOrder : list) {
                    eipWorkOrder.setIoflag(eipWorkOrder.getIoflag() == null ? "1" : eipWorkOrder.getIoflag());
                    EipWorkOrder eipWorkOrderByWoNo = eipWorkOrderService.selectByWoNo(eipWorkOrder.getWoNo());
                    if (eipWorkOrderByWoNo == null) {
                        eipWorkOrderService.save(eipWorkOrder);
                    } else {
                        LambdaQueryWrapper<EipWorkOrder> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(EipWorkOrder::getWoNo, eipWorkOrder.getWoNo());
                        eipWorkOrderService.update(eipWorkOrder, queryWrapper);
                    }
                }
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
//                return Result.error("文件导入失败:" + e.getMessage());
                return Result.error("文件导入失败:请检查excel模板是否正确");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /**
     * 导出excel 工单
     *
     * @param request      参数
     * @param eipWorkOrder 工单
     */
    @ApiOperation("导出excel 工单")
    @AutoLog(value = "QueryExport")
    @RequestMapping(method = RequestMethod.GET, value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, EipWorkOrder eipWorkOrder) {
        return super.exportXls(request, eipWorkOrder, EipWorkOrder.class, "eip_work_order");
    }
}